package com.inifitness.tenant.core.system.service.impl;


import java.util.List;

import jakarta.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inifitness.tenant.core.system.mapper.BizUserAcctRoleMapper;
import com.inifitness.tenant.core.system.model.entity.BizUserAcctRole;
import com.inifitness.tenant.core.system.service.BizUserAcctRoleService;

import cn.hutool.core.collection.CollUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

@Service
public class BizUserAcctRoleServiceImpl extends
    ServiceImpl<BizUserAcctRoleMapper, BizUserAcctRole> implements BizUserAcctRoleService {

  @Resource
  @Lazy
  private BizUserAcctRoleService bizUserAcctRoleService;

  /**
   * 保存用户角色
   *
   * @param userId
   * @param roleIds
   * @return
   */
  @Override
  public boolean saveUserRoles(Long userId, List<Long> roleIds) {

    if (userId == null || CollUtil.isEmpty(roleIds)) {
      return false;
    }

    // 用户原角色ID集合
    List<Long> userRoleIds = this.list(new LambdaQueryWrapper<BizUserAcctRole>()
            .eq(BizUserAcctRole::getUserId, userId))
        .stream()
        .map(BizUserAcctRole::getRoleId)
        .toList();

    // 新增用户角色
    List<Long> saveRoleIds;
    if (CollUtil.isEmpty(userRoleIds)) {
      saveRoleIds = roleIds;
    } else {
      saveRoleIds = roleIds.stream()
          .filter(roleId -> !userRoleIds.contains(roleId))
          .toList();
    }

    List<BizUserAcctRole> saveUserRoles = saveRoleIds
        .stream()
        .map(roleId -> new BizUserAcctRole(userId, roleId))
        .toList();
    bizUserAcctRoleService.saveBatch(saveUserRoles);

    // 删除用户角色
    if (CollUtil.isNotEmpty(userRoleIds)) {
      List<Long> removeRoleIds = userRoleIds.stream()
          .filter(roleId -> !roleIds.contains(roleId))
          .toList();

      if (CollUtil.isNotEmpty(removeRoleIds)) {
        this.remove(new LambdaQueryWrapper<BizUserAcctRole>()
            .eq(BizUserAcctRole::getUserId, userId)
            .in(BizUserAcctRole::getRoleId, removeRoleIds)
        );
      }
    }
    return true;

  }

  /**
   * 判断角色是否存在绑定的用户
   *
   * @param roleId 角色ID
   * @return true：已分配 false：未分配
   */
  @Override
  public boolean hasAssignedUsers(Long roleId) {
    int count = this.baseMapper.countUserAcctsForRole(roleId);
    return count > 0;
  }
}
